package main

import (
	"fmt"
	"math"
	"strconv"
)

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	str1, len1 := nodeToNumber(l1)
	str2, len2 := nodeToNumber(l2)

	fmt.Println(str1, str2)

	if len1 < len2 {
		//交换顺序，确保长的数据在前
		str1, str2 = str2, str1
		len1, len2 = len2, len1
	}
	maxlen := len(fmt.Sprintf("%d", math.MaxInt64))

	str := ""
	if len1 > len2 && len1 > maxlen {

		str = str1[:maxlen-1]
		num1Str := str1[maxlen-1:]
		nsLen := len(num1Str)
		num1, _ := strconv.ParseInt(num1Str, 10, 64)
		num2, _ := strconv.ParseInt(str2, 10, 64)
		str += fmt.Sprintf("%0"+strconv.Itoa(nsLen)+"d", num1+num2)
	} else {
		num1, _ := strconv.ParseInt(str1, 10, 64)
		num2, _ := strconv.ParseInt(str2, 10, 64)
		str += fmt.Sprintf("%d", num1+num2)
	}

	length := len(str)
	l3 := &ListNode{}
	lnext := l3
	for i := length - 1; i >= 0; i-- {
		fmt.Println(int(str[i]) - 48)
		if i == length-1 {
			lnext.Val = int(str[i]) - 48
		} else {
			lnext.Next = &ListNode{Val: int(str[i]) - 48}
			lnext = lnext.Next
		}
	}
	return l3
}

func nodeToNumber(node *ListNode) (string, int) {
	str := ""
	length := 0
	tNode := node
	for ; tNode != nil; tNode = tNode.Next {
		length++
		str = strconv.Itoa(tNode.Val) + str
	}
	return str, length
}

//[2,4,3]
//[5,6,4]
func main() {
	l1 := &ListNode{
		Val: 2,
		Next: &ListNode{
			Val: 4,
			Next: &ListNode{
				Val: 3,
			},
		},
	}
	l2 := &ListNode{
		Val: 5,
		Next: &ListNode{
			Val: 6,
		},
	}

	addTwoNumbers(l1, l2)

}
